package com.hh.jwtdemo.controller;

import com.hh.jwtdemo.service.SecureFileService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;

@RestController
@RequestMapping("/api/files")
public class FileController {

    @Autowired
    private SecureFileService fileStorage;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileId = fileStorage.storeFile(file);
            return ResponseEntity.ok(fileId);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("上传失败");
        }
    }

    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable String fileId,HttpServletResponse response) {
        response.setContentType("application/octet-stream");
        try (OutputStream out = response.getOutputStream()) {
            fileStorage.loadFile(fileId, out);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
